package com.ht.api.bigtask.impl.qywx;

import javax.sql.DataSource;

import com.ht.api.bigtask.BaseBigTask;
import com.ht.api.constant.CacheConstants;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.RedisUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取外部用户的会话同意情况
 * @author asq
 * @createTime 2025年3月27日 11:12:03
 */
@Slf4j
public class GetPermitExteranalUserList extends BaseBigTask {
	/** 接口ID：获取会话同意情况 */
	private static final long API_ID = 1907308595922472960L;

	@Override
	protected void doExecute(String appId, JSONObject context, Entity bean) {
		DataSource ds = getTenantDs(appId);
		
		// 查询已开启会话存档的客服列表
		DbList wxWorkUserList = Db.createSqlParser("wx_workuser").where("is_keep", 1).query(ds);
		for (Entity wxWorkUser : wxWorkUserList) {
			String userid = wxWorkUser.getStr("userid");
			DbList externalUseridList = Db.createSqlParser("wx_workuser_customer")
					.select("external_userid").where("userid", userid).query(ds);
			
			queryWwxThenSaveOpenData(ds, appId, userid, externalUseridList, 1);
		}
	}

	/**
	 * 分页获取会话同意情况，然后写入open_data
	 * @param ds 数据源
	 * @param appId 应用ID
	 * @param userid 客服ID
	 * @param externalUseridList 外部用户ID
	 * @param pageNum 页号，从1开始
	 */
	private void queryWwxThenSaveOpenData(DataSource ds, String appId, String userid, DbList externalUseridList, int pageNum) {
		JSONArray infoArr = JSONUtil.createArray();
		int pageStart = (pageNum - 1) * 100;
		int pageEnd = Math.min(pageStart + 100, externalUseridList.size());
		for (int i = pageStart; i < pageEnd; i++) {
			JSONObject info = JSONUtil.createObj();
			info.set("userid", userid);
			info.set("exteranalopenid", externalUseridList.get(i).getStr("external_userid"));
			infoArr.add(info);
		}
		
		if (!infoArr.isEmpty()) {
			JSONObject param = JSONUtil.createObj();
			param.set("info", infoArr);
			String str = OpenUtil.callByNoAssemble(getKeepAppId(appId), API_ID, param);
	
			JSONObject entity = JSONUtil.parseObj(str);
			Db.insert(ds, createOpenDataEntity(appId, API_ID, entity));
		}
		
		if (pageEnd < externalUseridList.size()) {
			queryWwxThenSaveOpenData(ds, appId, userid, externalUseridList, ++pageNum);
		}
	}
	
	/**
	 * 获取应用配置的会话存档应用ID
	 * @param appId 主应用ID
	 * @return
	 */
	private String getKeepAppId(String appId) {
		Entity app = RedisUtil.get(CacheConstants.KEY_APP + appId);
		JSONObject appConfig = JSONUtil.parseObj(app.getStr("config"));
		String addressBookAppId = appConfig.getStr("session_keep_id");
		if (addressBookAppId != null) {
			return addressBookAppId;
		} else {
			throw new HtException("应用未配置对应的会话存档应用ID，无法获取会话内容存档开启成员列表");
		}
	}

}
